import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useUserStore = defineStore(
  'user',
  () => {
    // 项目配置
    //邀请链接
    const inviteLink = ref('https://u.x-verse.cn.lu/download/download.html?invitecode=');
    // 状态
    const userInfo = ref(null);
    const token = ref('');
    const isLoggedIn = ref(false);
    const currentLanguage = ref('en-US'); // 当前语言，默认为英文

    // 动作
    const setUserInfo = (info) => {
      userInfo.value = info;
      console.log('====>userInfo', userInfo.value);
      isLoggedIn.value = !!info;
    };

    const setToken = (newToken) => {
      token.value = newToken;
      // 可以在这里保存到本地存储
      if (newToken) {
        uni.setStorageSync('token', newToken);
      } else {
        uni.removeStorageSync('token');
      }
    };

    const logout = () => {
      userInfo.value = null;
      token.value = '';
      isLoggedIn.value = false;
      uni.removeStorageSync('token');
    };

    const updateUserInfo = (newInfo) => {
      if (userInfo.value) {
        userInfo.value = { ...userInfo.value, ...newInfo };
      }
    };

    const setLanguage = (language) => {
      currentLanguage.value = language;
      uni.setStorageSync('currentLanguage', language);
    };

    return {
      // 状态
      userInfo,
      token,
      isLoggedIn,
      inviteLink,
      currentLanguage,
      // 动作
      setUserInfo,
      setToken,
      logout,
      updateUserInfo,
      setLanguage
    };
  },
  {
    // 持久化配置
    persist: {
      key: 'user-store',
      storage: {
        getItem: (key) => uni.getStorageSync(key),
        setItem: (key, value) => uni.setStorageSync(key, value),
        removeItem: (key) => uni.removeStorageSync(key)
      },
      // 只持久化指定的状态
      paths: ['userInfo', 'token', 'isLoggedIn', 'currentLanguage']
    }
  }
);
